﻿/**************************************************************
 *
 * 唯一标识：1216e3ca-e226-48d0-9e56-72f98ed8a694
 * 命名空间：Sgr.UPMS.Application.Commands.Users
 * 创建时间：2023/8/27 11:49:10
 * 机器名称：DESKTOP-S0D075D
 * 创建者：antho
 * 电子邮箱：fengqinhua2016@163.com
 * 描述：删除用户命令处理器
 *
 **************************************************************/

using MediatR;
using Sgr.Application.Commands;
using Sgr.Security.Tokens.Services;
using Sgr.UPMS.Domain.Users;
using System.Threading;
using System.Threading.Tasks;

namespace Sgr.UPMS.Application.Commands.Users
{
    /// <summary>
    /// 删除用户命令处理器
    /// </summary>
    public class DeleteUserCommandHandle : IRequestHandler<DeleteUserCommand, CommandResult<bool>>
    {
        public const int DeleteUserTokenTypeIndex = 1001;

        private readonly IUserManage _userManage;
        private readonly ITemporaryTokenService _temporaryTokenService;
        private readonly ICurrentUser _currentUser;

        public DeleteUserCommandHandle(IUserManage userManage,
            ITemporaryTokenService temporaryTokenService,
            ICurrentUser currentUser)
        {
            _userManage = userManage;
            _temporaryTokenService = temporaryTokenService;
            _currentUser = currentUser;
        }

        /// <summary>
        /// 处理删除用户命令
        /// </summary>
        /// <param name="request">命令请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>处理结果</returns>
        public async Task<CommandResult<bool>> Handle(DeleteUserCommand request, CancellationToken cancellationToken)
        {
            //二次密码验证
            if (!await _temporaryTokenService.ValidateAsync(
                    code: request.TemporaryToken,
                    tokenType: DeleteUserTokenTypeIndex,
                    content: null,
                    deviceFingerprint: _currentUser.DeviceFingerprint,
                    userId: _currentUser.Id,
                    cancellationToken: cancellationToken))
                return CommandResult.Invalid<bool>("二次密码验证的令牌验证失败");

            //执行删除
            if (!long.TryParse(_currentUser.Id, out var userId))
                return CommandResult.NotFound<bool>("未找到指定的用户");


            if (!await _userManage.DeleteUserAsync(request.UserId, userId, cancellationToken))
                return CommandResult.Error<bool>("删除用户过程中发生错误");

            // 返回成功结果
            return CommandResult.Success(true, "用户删除成功");
        }
    }
}